<template>
  <div class="page-container">
    <div class="content-wrapper">
      <!-- 标题区域 -->
      <div class="page-title">
        <div class="title-indicator"></div>
        <h2>机构管理</h2>
      </div>

      <!-- 筛选和操作区域 -->
      <div class="filter-container">
        <div class="filter-row">
          <el-input
              v-model="searchText"
              placeholder="请输入关键字"
              class="search-input"
              :suffix-icon="Search"
              @change="initData"
          ></el-input>
          <div style="flex: 1"></div>
          <div class="action-buttons">
            <el-button type="primary" @click="openCreateDialog" size="large">
              新增机构
            </el-button>
            <el-button type="success" @click="openDashboard" size="large">
              数据统计
            </el-button>
            <el-button @click="exportData" size="large">
              导出
            </el-button>
          </div>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          :data="institutions"
          style="width: 100%"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>

          <el-table-column prop="id" label="编号"></el-table-column>

          <el-table-column label="机构图片">
            <template #default="{ row }">
              <div class="institution-logo">
                <img
                  :src="row.image || defaultLogo"
                  :alt="row.name"
                  class="logo-image"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="机构名称"></el-table-column>
          <el-table-column prop="principal" label="负责人姓名"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column prop="address" label="机构地址"></el-table-column>

          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="editInstitution(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="deleteInstitution(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <div class="pagination-info">
          <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 25, 30]"
              layout="total, sizes, prev, pager, next, jumper"
              v-model:total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="institutionForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="机构名称" prop="name">
          <el-input v-model="institutionForm.name" placeholder="请输入机构名称" />
        </el-form-item>

        <el-form-item label="负责人姓名" prop="contactPerson">
          <el-input v-model="institutionForm.principal" placeholder="请输入负责人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="institutionForm.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="机构地址" prop="address">
          <el-input
            v-model="institutionForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入机构地址"
          />
        </el-form-item>

        <el-form-item label="机构图片">
          <el-upload
            class="logo-uploader"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
          >
            <img v-if="institutionForm.image" :src="institutionForm.image" class="logo-preview" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 响应式数据
const institutions = ref([])
const searchText = ref('')

// 分页数据
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(5);
const handleSizeChange = (val) => {
  pageSize.value = val;
  initData();
}

const handleCurrentChange = (val) => {
  pageNum.value = val;
  initData();
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增机构')
const formRef = ref()
const isEdit = ref(false)
const currentEditId = ref(null)

// 表单数据
const institutionForm = ref({})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入机构名称', trigger: 'blur' }
  ],
  principal: [
    { required: true, message: '请输入负责人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入机构地址', trigger: 'blur' }
  ]
}

// 默认机构logo
const defaultLogo = ''


// 初始化数据
const initData = async () => {
  try {
    // 构建请求对象，匹配后端InstitutionSearchDTO结构
    const searchDTO = {
      keyWord: searchText.value || null  // 注意字段名是keyWord，与DTO保持一致
    }

    const response = await axios.post(`/institution/getInstitutionInfo/${pageNum.value}/${pageSize.value}`, searchDTO)

    institutions.value = response.data.data || []
    total.value = response.data.total || 0

    if (institutions.value.length === 0 && searchText.value) {
      ElMessage.info('未找到匹配的机构信息')
    }
  } catch (error) {
    console.error('获取机构信息失败:', error)
    ElMessage.error('获取机构信息失败，请稍后重试')
    institutions.value = []
    total.value = 0
  }
}

// 选择处理
const handleSelectionChange = (selection) => {
  console.log('选中的机构:', selection)
}

// 打开新增弹窗
const openCreateDialog = () => {
  dialogTitle.value = '新增机构'
  isEdit.value = false
  institutionForm.value = {
    name: '',
    contactPerson: '',
    phone: '',
    address: '',
    logo: '',
    status: 1
  }
  dialogVisible.value = true
}

// 编辑机构
const editInstitution = (row) => {
  dialogTitle.value = '编辑机构'
  isEdit.value = true
  currentEditId.value = row.id
  institutionForm.value = { ...row }
  dialogVisible.value = true
}

// 删除机构
const deleteInstitution = (row) => {
  ElMessageBox.confirm(
    `确定要删除机构"${row.name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    axios.delete(`/institution/deleteInstitution/${row.id}`).then(resp => {
      ElMessage.success(resp.data)
      initData()
    })
    initData()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value.resetFields()
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        axios.put(`/institution/updateInstitution`, institutionForm.value).then(resp => {
          ElMessage.success(resp.data)
          initData()
        })
      } else {
        axios.post(`/institution/addInstitution`, institutionForm.value).then(resp => {
          ElMessage.success(resp.data)
          initData()
        })
      }
      closeDialog()
    }
  })
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleUploadSuccess = (response) => {
  institutionForm.value.logo = response.url
  ElMessage.success('图片上传成功')
}

// 导出数据
const exportData = () => {
  ElMessage.info('导出功能开发中...')
}

// 打开数据统计页面
const openDashboard = () => {
  router.push('/main/dashboard')
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.title-indicator {
  width: 4px;
  height: 20px;
  background-color: #1890ff;
  margin-right: 8px;
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.filter-container {
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
}

.institution-logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
  color: #666;
}

.jump-input {
  width: 60px;
}

.logo-uploader {
  display: inline-block;
}

.logo-uploader .logo-preview {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #dcdfe6;
}

.logo-uploader .logo-uploader-icon {
  width: 100px;
  height: 100px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #8c939d;
  cursor: pointer;
  transition: all 0.3s;
}

.logo-uploader .logo-uploader-icon:hover {
  border-color: #409eff;
  color: #409eff;
}

/* Element Plus 样式覆盖 */
:deep(.el-table th) {
  background-color: #fafafa;
  color: #262626;
  font-weight: 600;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #f5f5f5;
}

:deep(.el-button--primary.is-link) {
  color: #1890ff;
}

:deep(.el-button--primary.is-link:hover) {
  color: #40a9ff;
}

:deep(.el-button--danger.is-link) {
  color: #ff4d4f;
}

:deep(.el-button--danger.is-link:hover) {
  color: #ff7875;
}

:deep(.el-switch.is-checked .el-switch__core) {
  background-color: #52c41a;
  border-color: #52c41a;
}
</style>